<?php

$csv_terminated = "\n";
$csv_separator = ",";
$csv_enclosed = '"';
$csv_escaped = "\\";
$fields_cnt = 47;
$schema_insert = '';
$filename = 'worthlessshares.csv';
$line = array('LineNo','CommonID',"OrderNo", "BrokerReference", "CompanyName", "CompanyCode", "RegdName1", "RegdName2", 
    "RegdName3", "RegdName4", "RegdName5", "RegdAd1", "RegdAd2", "RegdAd3", "RegdAd4", "RegdAd5", "NumFigures", "NumWords",
    "Security", "SRN", "HIN", "BrokerNameAdd", "NewAd1", "NewAd2", "NewAd3", "NewAd4", "NewAd5", "Email","Tel", "CCName", 
    "CCNumber", "CCExpiry", "CCVerif", "CCType", "AmtRecd", "Gross", "GST", "Date", "DateDocRecd", "DateForConv", 
    "DateForRego", "Registry", "Action", "Status", "parcelNumber", "docfile", "bankAuthorisationNumber");
for ($i = 0; $i < $fields_cnt; $i++) {
   // echo $line[$i];
    $l = $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, stripslashes($line[$i])) . $csv_enclosed;
    $schema_insert .= $l;
    $schema_insert .= $csv_separator;
} // end for

$out = trim(substr($schema_insert, 0, -1));
$out .= $csv_terminated;
foreach ($worthlessshares as $codetail) {
    $schema_insert = '';
    for ($j = 0; $j < $fields_cnt; $j++) {
        if ($codetail['WorthlessShare'][$line[$j]] == '0' || $codetail['WorthlessShare'][$line[$j]] != '') {
            if ($csv_enclosed == '') {
                $schema_insert .= $codetail['WorthlessShare'][$line[$j]];
            } else {
                $schema_insert .= $csv_enclosed .
                        str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $codetail['WorthlessShare'][$line[$j]]) . $csv_enclosed;
            }
        } else {
            $schema_insert .= '';
        }

        if ($j < $fields_cnt - 1) {
            $schema_insert .= $csv_separator;
        }
    }
    $out .= $schema_insert;
    $out .= $csv_terminated;
}

header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Length: " . strlen($out));
// Output to browser with appropriate mime type, you choose ;)
header("Content-type: text/x-csv");
header("Content-Disposition: attachment; filename=$filename");
echo $out;
exit;
?>